<template>
  <t-skeleton :loading="loading">
    <div style="margin-bottom: var(--td-comp-margin-s)">
      <t-button
        v-if="measureInfo.result !== 2&&measureInfo.result !==1"
        v-permission="['system:order-designer:save-design-info']"
        @click="
          handleOpenDialog('create', {
            orderId: orderDetails.orderId || orderDetails.id,
            logType: 'measure',
            secondTypeFileUrl: {},
            actualArea: measureInfo.actualArea,
            remark: measureInfo.remark,
          })
        "
      >
        上传量房信息
      </t-button>
    </div>
    <t-alert v-if="measureInfo.actualArea && measureInfo.remark" style="margin-bottom: var(--td-comp-margin-s)">
      <span>实际面积(㎡)：{{ measureInfo.actualArea }}，</span>
      <span>备注：{{ measureInfo.remark }}</span>
      <span v-if="measureInfo.result !== null" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(measureInfo.result - 1).theme">{{
          getTagThemeAndLabel(measureInfo.result - 1).label
        }}</t-tag>
      </span>
    </t-alert>
    <div class="content">
      <t-anchor
        class="anchor"
        :container="containerClassName"
        :target-offset="50"
        @click="({ e }) => e.preventDefault()"
      >
        <t-anchor-item
          v-for="_ in dictionaryStore.get('decoration_design_order_measure_class')"
          :key="_.value"
          :href="`#measureInfo${_.value}`"
          :title="_.label"
        />
      </t-anchor>
      <t-collapse class="list" default-expand-all>
        <t-collapse-panel
          v-for="_ in dictionaryStore.get('decoration_design_order_measure_class')"
          :id="`measureInfo${_.value}`"
          :key="_.value"
          :header="_.label"
        >
          <template v-for="info in measureInfoList.filter((item) => item.fileSecondType === _.value)" :key="info.id">
            <t-divider align="left">
              {{ userStore.getUserNameById(info.creator) }} {{ dayjs(info.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </t-divider>
            <!-- 图片预览 -->
            <image-viewer :images="info.fileUrl.map((f: Record<string, string>) => f.url)" />
          </template>
        </t-collapse-panel>
      </t-collapse>
    </div>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData }"
      :api-map="{ create: createDesignInfo }"
      header="上传量房信息"
      width="1000px"
      :on-before-save-data="handleDialogSaveData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-collapse style="margin: 20px 0">
        <t-collapse-panel
          v-for="_ in dictionaryStore.get('decoration_design_order_measure_class')"
          :key="_.value"
          :header="_.label"
        >
          <upload v-model:files="formData.secondTypeFileUrl[_.value]" accept="image/*" multiple theme="image" />
        </t-collapse-panel>
      </t-collapse>
      <t-form-item label="实际面积(㎡)" name="actualArea" :rules="[{ required: true, message: '请输入实际面积' }]">
        <t-input-number
          v-model:value="formData.actualArea"
          placeholder="请输入实际面积"
          clearable
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="备注" name="remark" :rules="[{ required: true, message: '请输入备注' }]">
        <t-textarea v-model:value="formData.remark" placeholder="请输入备注" />
      </t-form-item>
    </custom-dialog>
  </t-skeleton>
  <!-- 粘性审批对话框 -->
  <sticky-approve-dialog ref="stickyApproveDialogRef5" :order-id="orderDetails.orderId || orderDetails.id" approve-type="5" />
  <sticky-approve-dialog ref="stickyApproveDialogRef11" :order-id="orderDetails.orderId || orderDetails.id" approve-type="11" />
  <!-- 发起人 -->
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog1Style"  ref="stickyInitApproveDialogRef5" :order-id="orderDetails.orderId || orderDetails.id" approve-type="5" />
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog2Style" ref="stickyInitApproveDialogRef11" :order-id="orderDetails.orderId || orderDetails.id" approve-type="11" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, inject, onMounted, reactive, Ref, ref, useTemplateRef, watch } from 'vue';

import { createDesignInfo, getDesignInfoList } from '@/api/order/details';
import CustomDialog from '@/components/custom/dialog/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import StickyInitApproveDialog from '@/pages/approve/components/sticky-init-approve-dialog.vue';
import { useDictionaryStore, useUserStore } from '@/store';

// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 订单详情
const orderDetails = inject<Ref<Record<string, any>>>('orderDetails');
// 容器类名
const containerClassName = window.document.getElementsByClassName('view-order-scroll').length
  ? '.view-order-scroll'
  : '.tdesign-starter-layout';
// 加载状态
const loading = ref(false);
// 量房信息列表
const measureInfoList = ref([]);
// 量房信息
const measureInfo = reactive({
  actualArea: undefined,
  remark: '',
  result: null,
});
// 根据审批状态获取标签样式以及文字
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: any) => {
  const map = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};
// 处理获取量房信息列表
const handleGetMeasureInfoList = () => {
  loading.value = true;
  const params = {
    orderId: orderDetails.value.orderId || orderDetails.value.id,
    logType: 'measure',
  };
  getDesignInfoList(params)
    .then((data) => {
      if (!data) return;
      measureInfoList.value = data.fileUrls;
      measureInfo.actualArea = data.actualArea;
      measureInfo.remark = data.remark;
      measureInfo.result = data.result;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
onMounted(() => {
  handleGetMeasureInfoList();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  // 设置初始值
  dictionaryStore.get('decoration_design_order_measure_class').forEach((item) => {
    params.secondTypeFileUrl[item.value] = [];
  });
  customDialogRef.value.open(mode, params);
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  // 查找存在的key
  const keys = dictionaryStore.get('decoration_design_order_measure_class');
  const existingKeys = keys
    .filter((item) => {
      return params.secondTypeFileUrl[item.value].length;
    })
    .map((item) => item.value);
  if (!existingKeys.length) {
    MessagePlugin.warning('请至少上传一种类型的照片！');
    return false;
  }
  return params;
};
// 处理对话框请求成功
const handleDialogRequestSuccess = () => {
  handleGetMeasureInfoList();
};
interface DialogRef {
  visible: boolean;
  open: () => void;
  close: () => void;
}
// 粘性审批对话框ref
const stickyApproveDialogRef5 = useTemplateRef('stickyApproveDialogRef5');
const stickyApproveDialogRef11 = useTemplateRef('stickyApproveDialogRef11');
const stickyInitApproveDialogRef11 = ref<DialogRef | null>(null);
const stickyInitApproveDialogRef5 = ref<DialogRef | null>(null);

onMounted(() => {
  const { approveType } = orderDetails.value;
  if (approveType === '5')   stickyApproveDialogRef5.value.open();
  if (approveType === '11')  stickyApproveDialogRef11.value.open();
  stickyInitApproveDialogRef5.value.open();
  stickyInitApproveDialogRef11.value.open();
});
// 判断是否同时显示多个对话框
const isMultiple = computed<boolean>(() => {
  return stickyInitApproveDialogRef11.value?.visible && stickyInitApproveDialogRef5.value?.visible;
});

// 第一个对话框的样式
const dialog1Style = computed(() => {
  if (isMultiple.value) {
    return { left: '40%' }; // 多个对话框时，第一个对话框靠左
  }
  return {}; // 单个对话框时，样式不变
});

// 第二个对话框的样式
const dialog2Style = computed(() => {
  if (isMultiple.value) {
    return { left: '60%' }; // 多个对话框时，第二个对话框靠右
  }
  return {}; // 单个对话框时，样式不变
});
</script>

<style lang="less" scoped>
.content {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  .anchor {
    width: 150px;
    position: sticky;
    top: 100px;
  }

  .list {
    width: 100%;
  }
}
</style>
